﻿using B.S.NewMedical.Api.Read.Application.Command.Order;
using B.S.NewMedical.Domain.Order;
using B.S.NewMedical.ErrorCode;
using B.S.NewMedical.Infrastructure.Interface;
using MediatR;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;

namespace B.S.NewMedical.Api.Read.Application.Handler.Order
{
    public class RegisterPageCommandHandle : IRequestHandler<RegisterPageCommand, ApiPageing<RegisterModel>>
    {
        private readonly IBaseRepository<RegisterModel> _registerRepository;

        public RegisterPageCommandHandle(IBaseRepository<RegisterModel> registerRepository)
        {
            _registerRepository = registerRepository;
        }

        public Task<ApiPageing<RegisterModel>> Handle(RegisterPageCommand request, CancellationToken cancellationToken)
        {
            var result = new ApiPageing<RegisterModel>();
            
            try
            {
                // 获取所有未删除的挂号订单
                var query = _registerRepository.GetAll().Where(x => x.IsDeleted == false);
                
                // 添加订单编号模糊查询条件
                if (!string.IsNullOrEmpty(request.OrderId))
                {
                    query = query.Where(x => x.OrderId.Contains(request.OrderId));
                }
                // 按提交时间倒序排列
                var orderedQuery = query.OrderByDescending(x => x.SubmitTime);
                
                // 计算总记录数
                result.TotaCount = orderedQuery.Count();
                
                // 计算总页数
                result.TotaPage = (int)Math.Ceiling((double)result.TotaCount / request.Size);
                
                // 分页查询数据
                result.PageData = orderedQuery
                    .Skip((request.Index - 1) * request.Size)
                    .Take(request.Size)
                    .ToList();
                
                result.Code = ApiEnum.Success;
                result.Msg = "挂号订单查询成功！";
            }
            catch (Exception ex)
            {
                result.Code = ApiEnum.Error;
                result.Msg = $"查询失败：{ex.Message}";
                result.PageData = new List<RegisterModel>();
            }
            
            return Task.FromResult(result);
        }
    }
}
